'''
乐活e生2019重大疾病保险
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,json
from common.helper import Helper
from pprint import pprint


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "乐活e生2019重大疾病保险"

    # 生成产品信息
    def genProductInfo(self):

        # 性别
        gender = ["男", "女"]
        # 保障计划 001 基础版 002 优选版 003 甄选版 004精选版
        plan = {

            # 基础版
            "base": {

                "packageCode": "PACK190678300001",
                "years": [str(i) for i in range(1, 61)]

            },
            # 优选版
            "optimization": {
                "packageCode": "PACK190666700002",
                "years": [str(i) for i in range(1, 56)]
            },
            # 甄选版
            "selection": {
                "packageCode": "PACK190692000003",
                "years": [str(i) for i in range(1, 41)]
            },
            # 精选版
            "selected": {
                "packageCode": "PACK190657900004",
                "years": [str(i) for i in range(18, 41)]
            },
            # 致优版
            "excellent": {

                "packageCode": "PACK190684200005",
                "years": [str(i) for i in range(18, 41)]
            },
            # 至尊款
            "stronger": {
                "packageCode": "PACK190606300006",
                "years": [str(i) for i in range(18, 40)]
            }

        }
        # 保障期限
        expire = "1"
        # 加购产品 ""不加购 1012005加购
        extra_product = ["", "1012005"]
        # 生成数据
        for k in plan:

            for v in product(plan[k]["years"], gender, extra_product):
                packageCode = plan[k]["packageCode"]

                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], packageCode, expire, v[2]))
                self.mysql._conn.commit()
                print("%s写入数据库成功" % self.name)

    # 执行爬虫
    def requestJson(self, dt=None):

        data = self.filterParam( dt )


        pprint( data )


        r = requests.post(url = domain[self.name]["url"],headers=domain[self.name]["header"],data=json.dumps( data ))

        if r.status_code == 200 and r.json()["status"] == 200:

            price = Helper.decimalParse( r.json()["data"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }

            self.mysql.updatePrice( data )

        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.randTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
    #过滤参数
    def filterParam(self,dt):

        if dt["packageCode"] == "PACK190678300001":

            data = {"bizNo": "INST191063626370", "productCode": "PRD190730261038", "packageCode": dt["packageCode"],
                    "optionProjectIdList": ["{0}".format("1012001") ] if  len(dt['extra_product'])>0  else [],
                    "premiumFactorList": [{"productPremiumFactorId": 1044001, "value": "1", "unit": "年"},
                                          {"productPremiumFactorId": 1044002,
                                           "value": "{year}-12-04".format(year=str(2019 - int(dt["year"]))),
                                           "unit": ""},
                                          {"productPremiumFactorId": 1044003, "value": dt["gender"], "unit": ""}],
                    "marketProductCode": "PRD190639946001"}

            return data

        elif dt["packageCode"] == "PACK190666700002":

            data = {"bizNo": "INST191063626370", "productCode": "PRD190730261038", "packageCode": dt["packageCode"],
                    "optionProjectIdList": ["{0}".format("1012002")] if  len(dt['extra_product'])>0  else [],
                    "premiumFactorList": [{"productPremiumFactorId": 1042007, "value": "1", "unit": "年"},
                                          {"productPremiumFactorId": 1042008,
                                           "value": "{year}-12-04".format(year=str(2019 - int(dt["year"]))),
                                           "unit": ""},
                                          {"productPremiumFactorId": 1042009, "value": dt["gender"], "unit": ""}],
                    "marketProductCode": "PRD190639946001"}

            return data

        elif dt["packageCode"] == "PACK190692000003":

            data = {"bizNo": "INST191063626370", "productCode": "PRD190730261038", "packageCode": dt["packageCode"],
                    "optionProjectIdList": ["{0}".format("1012003")] if  len(dt['extra_product'])>0  else [],
                    "premiumFactorList": [{"productPremiumFactorId": 1044004, "value": "1", "unit": "年"},
                                          {"productPremiumFactorId": 1044005,
                                           "value": "{year}-12-04".format(year=str(2019 - int(dt["year"]))),
                                           "unit": ""},
                                          {"productPremiumFactorId": 1044006, "value": dt["gender"], "unit": ""}],
                    "marketProductCode": "PRD190639946001"}

            return data

        elif dt["packageCode"] == "PACK190657900004":

            data = {"bizNo": "INST191063626370", "productCode": "PRD190730261038", "packageCode": dt["packageCode"],
                    "optionProjectIdList": ["{0}".format("1012004")] if  len(dt['extra_product'])>0  else [],
                    "premiumFactorList": [{"productPremiumFactorId": 1042010, "value": "1", "unit": "年"},
                                          {"productPremiumFactorId": 1042011,
                                           "value": "{year}-12-04".format(year=str(2019 - int(dt["year"]))),
                                           "unit": ""},
                                          {"productPremiumFactorId": 1042012, "value": dt["gender"], "unit": ""}],
                    "marketProductCode": "PRD190639946001"}

            return data

        elif dt["packageCode"] == "PACK190684200005":

            data = {"bizNo": "INST191063626370", "productCode": "PRD190730261038", "packageCode": dt["packageCode"],
                    "optionProjectIdList": ["{0}".format("1012005")] if  len(dt['extra_product'])>0  else [],
                    "premiumFactorList": [{"productPremiumFactorId": 1042013, "value": "1", "unit": "年"},
                                          {"productPremiumFactorId": 1042014,
                                           "value": "{year}-12-04".format(year=str(2019 - int(dt["year"]))),
                                           "unit": ""},
                                          {"productPremiumFactorId": 1042015, "value": dt["gender"], "unit": ""}],
                    "marketProductCode": "PRD190639946001"}

            return data

        elif dt["packageCode"] == "PACK190606300006":

            data = {"bizNo": "INST191063626370", "productCode": "PRD190730261038", "packageCode": dt["packageCode"],
                    "optionProjectIdList": ["{0}".format("1012006")] if  len(dt['extra_product'])>0  else [],
                    "premiumFactorList": [{"productPremiumFactorId": 1042016, "value": "1", "unit": "年"},
                                          {"productPremiumFactorId": 1042017,
                                           "value": "{year}-12-04".format(year=str(2019 - int(dt["year"]))),
                                           "unit": ""},
                                          {"productPremiumFactorId": 1042018, "value":dt["gender"], "unit": ""}],
                    "marketProductCode": "PRD190639946001"}



            return data
